package io.hilo.example.app.backup;

import java.io.IOException;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

/**
 * @deprecated use GlobalControllerInterceptor replace
 *             <p>
 *             因为RequestBodyAdvice只能拦截有@RequestBody的接口，局限性太大！！
 * 
 * @author zollty
 * @since 2022年1月25日
 */
// @Component
@ControllerAdvice(basePackages = "xxx") // 声明该类要处理的包路径
public class AppRequestBodyAdvice implements RequestBodyAdvice {
    private static final Logger log = LoggerFactory.getLogger(AppRequestBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) {

        log.warn("RequestBodyAdvice: supports................\n"
                        + "MethodParameter: {}, \ntargetType: {}, \nconverterType: {}",
                methodParameter, targetType, converterType);

        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
            Type targetType, Class<? extends HttpMessageConverter<?>> converterType)
            throws IOException {

        log.warn("RequestBodyAdvice: beforeBodyRead................\nMethodParameter: {}",
                    parameter);

        // MethodParameter: method 'hello' parameter 0

        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage,
            MethodParameter parameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) {

        log.warn(
                "RequestBodyAdvice: afterBodyRead................\nMethodParameter: {}, body: {}",
                    parameter, body);

        // MethodParameter: method 'hello' parameter 0,
        // body: com.xxx.demo.pojo.LoginUser@795425cd

        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage,
            MethodParameter parameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) {

        log.warn(
                "RequestBodyAdvice: handleEmptyBody................\nMethodParameter: {}, body: {}",
                    parameter, body);
        // MethodParameter: method 'hello' parameter 0, body: null

        return null;
    }

}
